'use client';

import { useState, useEffect } from 'react';
import GlassCard from '@/components/ui/GlassCard';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { Users, Plus, Edit, Trash2, Search, Shield, User as UserIcon, Mail, Building } from 'lucide-react';
import toast from 'react-hot-toast';
import { useAuthStore } from '@/store/authStore';

interface User {
  id: string;
  username: string;
  email?: string;
  full_name?: string;
  role: 'admin' | 'user' | 'manager';
  department?: string;
  is_active: boolean;
  created_at: string;
}

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    full_name: '',
    role: 'user' as 'admin' | 'user' | 'manager',
    department: '',
  });
  const [deleteConfirm, setDeleteConfirm] = useState<{isOpen: boolean, userId: string, username: string}>({
    isOpen: false,
    userId: '',
    username: ''
  });

  const currentUser = useAuthStore((state) => state.user);
  const isAdmin = currentUser?.role === 'admin';

  useEffect(() => {
    loadUsers();
  }, []);

  const loadUsers = async () => {
    setLoading(true);
    try {
      const { api } = await import('@/lib/api');
      const token = localStorage.getItem('access_token');
      
      const response = await api.get('/users/', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      
      setUsers(response.data);
    } catch (error: any) {
      console.error('Failed to load users:', error);
      toast.error('加载用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingUser(null);
      setFormData({
        username: '',
        email: '',
        password: '',
        full_name: '',
        role: 'user',
        department: '',
      });
    setShowModal(true);
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setFormData({
      username: user.username,
      email: user.email || '',
      password: '', // Don't show password
      full_name: user.full_name || '',
      role: user.role,
      department: user.department || '',
    });
    setShowModal(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.username) {
      toast.error('用户名不能为空');
      return;
    }

    if (!editingUser && !formData.password) {
      toast.error('创建用户时密码不能为空');
      return;
    }

    try {
      const { api } = await import('@/lib/api');
      const token = localStorage.getItem('access_token');

      const payload: any = {
        username: formData.username,
        email: formData.email || null,
        full_name: formData.full_name || null,
        role: formData.role,
        department: formData.department || null,
      };

      if (editingUser) {
        // Update existing user
        if (formData.password) {
          payload.password = formData.password;
        }
        
        await api.put(`/users/${editingUser.id}`, payload, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        
        toast.success('用户更新成功！');
      } else {
        // Create new user
        payload.password = formData.password;
        
        await api.post('/auth/register', payload, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        
        toast.success('用户创建成功！');
      }

      setShowModal(false);
      loadUsers();
    } catch (error: any) {
      console.error('Failed to save user:', error);
      const errorMsg = error.response?.data?.detail || error.message || '操作失败';
      toast.error(errorMsg);
    }
  };

  const handleDeleteClick = (userId: string, username: string) => {
    if (userId === currentUser?.id) {
      toast.error('不能删除自己的账号');
      return;
    }
    setDeleteConfirm({ isOpen: true, userId, username });
  };

  const handleDeleteConfirm = async () => {
    const { userId } = deleteConfirm;
    try {
      const { api } = await import('@/lib/api');
      const token = localStorage.getItem('access_token');

      await api.delete(`/users/${userId}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      toast.success('用户删除成功！');
      loadUsers();
    } catch (error: any) {
      console.error('Failed to delete user:', error);
      toast.error('删除用户失败');
    }
  };

  const filteredUsers = users.filter((user) =>
    user.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
    user.email?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    user.full_name?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (!isAdmin) {
    return (
      <GlassCard className="p-8 text-center">
        <Shield className="h-16 w-16 mx-auto mb-4 text-red-500" />
        <h2 className="text-2xl font-bold mb-2">权限不足</h2>
        <p className="text-gray-600 dark:text-white/70">只有管理员才能访问用户管理页面</p>
      </GlassCard>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
            <Users className="h-8 w-8 text-indigo-600 dark:text-indigo-400" />
            用户管理
          </h1>
          <p className="mt-2 text-gray-600 dark:text-white/70">
            管理系统用户、角色和权限
          </p>
        </div>
        <button
          onClick={handleCreate}
          className="glass px-6 py-3 rounded-xl font-semibold flex items-center gap-2 hover:scale-105 transition-all duration-300 bg-gradient-to-r from-indigo-500 to-purple-500 text-white border-none shadow-lg hover:shadow-xl"
        >
          <Plus className="h-5 w-5" />
          新建用户
        </button>
      </div>

      {/* Search */}
      <GlassCard className="p-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
          <input
            type="text"
            placeholder="搜索用户名、邮箱或姓名..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 bg-transparent border-none focus:outline-none text-gray-900 dark:text-white placeholder-gray-400"
          />
        </div>
      </GlassCard>

      {/* Users List */}
      <GlassCard className="p-6">
        {loading ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
            <p className="mt-4 text-gray-600 dark:text-white/70">加载中...</p>
          </div>
        ) : filteredUsers.length === 0 ? (
          <div className="text-center py-12">
            <Users className="h-16 w-16 mx-auto mb-4 text-gray-400" />
            <p className="text-gray-600 dark:text-white/70">
              {searchQuery ? '未找到匹配的用户' : '暂无用户'}
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200/50 dark:border-white/10">
                  <th className="text-left py-3 px-4 font-semibold text-gray-700 dark:text-white/90">用户名</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700 dark:text-white/90">姓名</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700 dark:text-white/90">邮箱</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700 dark:text-white/90">角色</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700 dark:text-white/90">部门</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700 dark:text-white/90">创建时间</th>
                  <th className="text-right py-3 px-4 font-semibold text-gray-700 dark:text-white/90">操作</th>
                </tr>
              </thead>
              <tbody>
                {filteredUsers.map((user) => (
                  <tr
                    key={user.id}
                    className="border-b border-gray-200/30 dark:border-white/5 hover:bg-gray-50/50 dark:hover:bg-white/5 transition-colors"
                  >
                    <td className="py-4 px-4">
                      <div className="flex items-center gap-2">
                        <UserIcon className="h-4 w-4 text-indigo-500" />
                        <span className="font-medium text-gray-900 dark:text-white">{user.username}</span>
                      </div>
                    </td>
                    <td className="py-4 px-4 text-gray-600 dark:text-white/70">
                      {user.full_name || '-'}
                    </td>
                    <td className="py-4 px-4">
                      <div className="flex items-center gap-2 text-gray-600 dark:text-white/70">
                        {user.email ? (
                          <>
                            <Mail className="h-4 w-4" />
                            {user.email}
                          </>
                        ) : (
                          '-'
                        )}
                      </div>
                    </td>
                    <td className="py-4 px-4">
                      <span
                        className={`px-3 py-1 rounded-full text-xs font-semibold ${
                          user.role === 'admin'
                            ? 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-300'
                            : 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300'
                        }`}
                      >
                        {user.role === 'admin' ? '管理员' : user.role === 'manager' ? '经理' : '普通用户'}
                      </span>
                    </td>
                    <td className="py-4 px-4">
                      <div className="flex items-center gap-2 text-gray-600 dark:text-white/70">
                        {user.department ? (
                          <>
                            <Building className="h-4 w-4" />
                            {user.department}
                          </>
                        ) : (
                          '-'
                        )}
                      </div>
                    </td>
                    <td className="py-4 px-4 text-gray-600 dark:text-white/70 text-sm">
                      {new Date(user.created_at).toLocaleDateString('zh-CN')}
                    </td>
                    <td className="py-4 px-4">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handleEdit(user)}
                          className="p-2 rounded-lg hover:bg-indigo-50 dark:hover:bg-white/10 text-indigo-600 dark:text-indigo-400 transition-colors"
                          title="编辑"
                        >
                          <Edit className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => handleDeleteClick(user.id, user.username)}
                          disabled={user.id === currentUser?.id}
                          className="p-2 rounded-lg hover:bg-red-50 dark:hover:bg-white/10 text-red-600 dark:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                          title={user.id === currentUser?.id ? '不能删除自己' : '删除'}
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </GlassCard>

      {/* Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <GlassCard className="w-full max-w-lg p-6 animate-fade-in">
            <h2 className="text-2xl font-bold mb-6 text-gray-900 dark:text-white">
              {editingUser ? '编辑用户' : '新建用户'}
            </h2>
            
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-sm font-semibold mb-2 text-gray-700 dark:text-white/90">
                  用户名 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={formData.username}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  className="w-full px-4 py-2.5 rounded-xl glass border border-gray-200/40 dark:border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-gray-900 dark:text-white"
                  required
                  disabled={!!editingUser}
                />
              </div>

              <div>
                <label className="block text-sm font-semibold mb-2 text-gray-700 dark:text-white/90">
                  密码 {editingUser && '(留空则不修改)'}
                  {!editingUser && <span className="text-red-500">*</span>}
                </label>
                <input
                  type="password"
                  value={formData.password}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  className="w-full px-4 py-2.5 rounded-xl glass border border-gray-200/40 dark:border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-gray-900 dark:text-white"
                  required={!editingUser}
                />
              </div>

              <div>
                <label className="block text-sm font-semibold mb-2 text-gray-700 dark:text-white/90">
                  姓名
                </label>
                <input
                  type="text"
                  value={formData.full_name}
                  onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
                  className="w-full px-4 py-2.5 rounded-xl glass border border-gray-200/40 dark:border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-sm font-semibold mb-2 text-gray-700 dark:text-white/90">
                  邮箱
                </label>
                <input
                  type="text"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  className="w-full px-4 py-2.5 rounded-xl glass border border-gray-200/40 dark:border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-sm font-semibold mb-2 text-gray-700 dark:text-white/90">
                  角色 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.role}
                  onChange={(e) => setFormData({ ...formData, role: e.target.value as 'admin' | 'user' | 'manager' })}
                  className="w-full px-4 py-2.5 rounded-xl glass border border-gray-200/40 dark:border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-gray-900 dark:text-white"
                  required
                >
                  <option value="user">普通用户</option>
                  <option value="manager">经理</option>
                  <option value="admin">管理员</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-semibold mb-2 text-gray-700 dark:text-white/90">
                  部门
                </label>
                <input
                  type="text"
                  value={formData.department}
                  onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                  className="w-full px-4 py-2.5 rounded-xl glass border border-gray-200/40 dark:border-white/20 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-gray-900 dark:text-white"
                />
              </div>

              <div className="flex gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  className="flex-1 px-4 py-2.5 rounded-xl glass border border-gray-200/40 dark:border-white/20 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors font-semibold text-gray-700 dark:text-white/90"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="flex-1 px-4 py-2.5 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-500 text-white font-semibold hover:scale-105 transition-all duration-300 shadow-lg hover:shadow-xl"
                >
                  {editingUser ? '更新' : '创建'}
                </button>
              </div>
            </form>
          </GlassCard>
        </div>
      )}

      {/* 删除确认对话框 */}
      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, userId: '', username: '' })}
        onConfirm={handleDeleteConfirm}
        title="删除用户"
        message={`确定要删除用户"${deleteConfirm.username}"吗？此操作不可恢复。`}
        confirmText="删除"
        cancelText="取消"
        variant="danger"
      />
    </div>
  );
}
